﻿using MediatR;
using RedDragon.Common.Domain.Enterprise;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Department
{
    /// <summary>
    /// 无条件获取全部部门
    /// </summary>
    public class SearchAllDepartmentHandler : IRequestHandler<SearchAllDepartmentCommand, Result>
    {
        /// <summary>
        /// 部门仓储
        /// </summary>
        private readonly IBaseRepository<Departments> _departmentRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchAllDepartmentHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="departmentRepository"></param>
        /// <param name="logger"></param>
        public SearchAllDepartmentHandler(IBaseRepository<Departments> departmentRepository,
                                           ILogger<SearchAllDepartmentHandler> logger)
        {
            _departmentRepository = departmentRepository;
            _logger = logger;
        }

        /// <summary>
        /// 无条件获取全部部门
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(SearchAllDepartmentCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                //根据主键ID获取部门上级
                var query = await (await _departmentRepository.GetAll()).ToListAsync();
                if (query.Count > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = query;
                    result.Msg = "无条件获取全部部门信息成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "无条件获取全部部门信息异常" + ex.Message;
                _logger.LogError("无条件获取全部部门信息异常" + ex.Message);
            }
            return result;
        }
    }
}
